package com.lwj.test.xml;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLOperate {

    private File file;
    private SAXReader reader;
    private Document document;
    
    public XMLOperate(){
	
    }
    public XMLOperate(File file){
	this.file = file;
    }
    
    private void init() throws DocumentException{
	reader = new SAXReader();
	try {
	    document = reader.read(file);
	} catch (DocumentException e) {
	    //e.printStackTrace();
	    throw e;
	}
    }
    public String getXmlEncoding(){
	if(document==null){
	    try {
		init();
	    } catch (DocumentException e) {
		e.printStackTrace();
	    }
	}
	return document.getXMLEncoding();
    }
    public void read() throws DocumentException {
	try {
	    init();
	} catch (DocumentException e) {
	    e.printStackTrace();
	}
	
	//XMLVistor vistor = new XMLVistor();
	
	//element.accept(vistor);
	//System.out.println(element.getName());
	//System.out.println(element);
    }
    
    public void readByNodeName(String nodeName) throws DocumentException {
	try {
	    init();
	} catch (DocumentException e) {
	    e.printStackTrace();
	}
	if(nodeName==null||"".equals(nodeName)){
	    throw new DocumentException("节点名称为空!");
	}
	Element element = document.getRootElement();
	for (Iterator it = element.elementIterator(); it.hasNext();) {
	    Element e = (Element) it.next();
	    //System.out.println(e.getName());
	    if(e.getName().equalsIgnoreCase(nodeName)){
		List<Element> list = e.elements();
		for (Element element2 : list) {
		    //System.out.println(element2.attributes().size());
		    if(element2.attributes().size()>0){
			List<Attribute> list2 = element2.attributes();
			
			for (Attribute att : list2) {
			    System.out.println("--->"+att.getName());
			}
			break;
		    }else {
			System.out.println("fieldName: "+element2.getName());
		    }
		}
		break;
	    }
	}
    }
    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }
    
    public SAXReader getReader() {
        return reader;
    }
    public void setReader(SAXReader reader) {
        this.reader = reader;
    }
    public Document getDocument() {
        return document;
    }
    public void setDocument(Document document) {
        this.document = document;
    }
}
